import { RefObject } from 'react';
import { useCallback, useRef, useState } from 'react';

export const useStateWithRef = <T>(initialState: T): [T, (arg1: T) => void, RefObject<T>] => {
  const [state, _setState] = useState(initialState);
  const ref = useRef(state);
  const setState = useCallback((newState: T) => {
    if (typeof newState === 'function') {
      _setState((prevState: any) => {
        const computedState = newState(prevState);
        ref.current = computedState;
        return computedState;
      });
    } else {
      ref.current = newState;
      _setState(newState);
    }
  }, []);
  return [state, setState, ref];
};
